package org.metasketch.simulator.tools.channels;

import java.io.File;
import java.io.FileReader;
import java.util.List;
import java.util.Set;

import org.metasketch.demo.model.ActorRole;
import org.metasketch.demo.model.DEMOModel;
import org.metasketch.demo.model.TransactionKind;
import org.metasketch.simulator.petri.PetriNet;
import org.metasketch.simulator.petri.PetriNetSet;
import org.metasketch.simulator.petri.Transition;
import org.metasketch.simulator.resources.Resource;
import org.metasketch.simulator.resources.ResourceBank;
import org.metasketch.simulator.resources.ResourceBase;
import org.metasketch.simulator.resources.ResourceClass;
import org.metasketch.simulator.resources.ResourceRequirements;
import org.metasketch.simulator.tools.Registry;
import org.metasketch.simulator.tools.generic.Expression;
import org.metasketch.simulator.tools.generic.GenericInfo;
import org.metasketch.simulator.tools.generic.GenericInfoValidator;
import org.metasketch.simulator.tools.generic.ResourceProduction;
import org.metasketch.simulator.tools.generic.ResourceRequirement;
import org.metasketch.simulator.tools.generic.Variable;
import org.metasketch.simulator.transformation.PetriNetSimulationPackage;

import com.thoughtworks.xstream.XStream;

public class MainChannelDefinitionLoader {

	protected static XStream getXStream() {
		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);

		xstream.processAnnotations(Expression.class);
		xstream.processAnnotations(Variable.class);
		xstream.processAnnotations(ResourceRequirement.class);
		xstream.processAnnotations(ResourceProduction.class);

		xstream.processAnnotations(GenericInfo.class);
		xstream.processAnnotations(ChannelDefinition.class);

		xstream.processAnnotations(MainChannelsDefinition.class);

		return xstream;
	}

	protected static MainChannelsDefinition load(File file) throws Throwable {

		XStream xstream = getXStream();

		FileReader reader = new FileReader(file);
		MainChannelsDefinition cfg = (MainChannelsDefinition) xstream
				.fromXML(reader);
		reader.close();

		return cfg;

	}

	public static MainChannelsDefinition getResources(
			PetriNetSimulationPackage simulationPackage, File file)
			throws Throwable {
		MainChannelsDefinition cfg = load(file);

		ResourceBank bank = simulationPackage.getResources();
		// PetriNetSet petriNetSet = simulationPackage.getPetriNets();
		Registry reg = simulationPackage.getRegistry();

		List<ChannelDefinition> channels = cfg.getChannels();
		for (ChannelDefinition channel : channels) {

			// validate
			GenericInfoValidator.validate(channel, reg, bank);
			// test for resources
			reg.register(channel.getAlias(), channel);

		}

		return cfg;

	}

}
